import { Wristband } from "@/entity/wristband.entity";
import { WristbandAdv } from "@/entity/wristband_adv.entity";
import { WristbandAdvLast } from "@/entity/wristband_adv_last.entity";
import { Repository } from "typeorm";
import { v4 as uuidv4 } from 'uuid';
// 保存手环广播最终数据
export async function saveLastAdv(
    gw_mac: string,
    mac: string,
    rssi: number,
    data: Partial<WristbandAdv>,
    format: number,
    date: Date,
    wristbandRepo: Repository<Wristband>,
    wristbandLastAdvRepo: Repository<WristbandAdvLast>
): Promise<WristbandAdvLast | undefined> {
    try {
        // 检查 wristband 是否存在，如果不存在则插入
        await ensureWristbandExists(mac, wristbandRepo);

        // 准备 wristbandAdvLast 的数据
        const wristbandAdvLastData = {
            gw_mac,
            mac,
            rssi,
            format,
            time: new Date(),
            ...data
        };

        // 使用 upsert 方法插入或更新记录
        const savedRecord = await wristbandLastAdvRepo.upsert(wristbandAdvLastData, ['mac']);
        return savedRecord.generatedMaps[0] as WristbandAdvLast;
    } catch (err) {
        console.error('Error occurred while creating wristbandAdvLast:', err);
        // throw new Error('Failed to create wristbandAdvLast record');
    }
}


async function ensureWristbandExists(mac: string, wristbandRepo: Repository<Wristband>): Promise<void> {
    const existingWristband = await wristbandRepo.findOne({ where: { mac } });
    if (!existingWristband) {
        await wristbandRepo
            .createQueryBuilder()
            .insert()
            .into(Wristband)
            .values({
                id: uuidv4(),
                mac,
                time: new Date(),
            })
            .orIgnore() // 如果 mac 地址已存在则忽略
            .execute();
    }
}